// src/utils/eventBus.js
import { ref, watchEffect } from 'vue'
import config from "@/config"

const eventSource = ref(null)
const eventListeners = {} // type -> [callbacks]
const connectionStatus = ref('disconnected') // disconnected, connecting, connected

// 导出连接状态，方便组件监听
 export { connectionStatus }

// 初始化连接
export function initEventBus() {
  if (eventSource.value) {
    console.log('SSE 连接已存在，无需重复初始化')
    return
  }

  console.log('开始初始化 SSE 连接...')
  connectionStatus.value = 'connecting'

  try {
    eventSource.value = new EventSource(config.api + 'event/create-events')

    eventSource.value.onopen = () => {
      console.log('SSE 连接已建立')
      connectionStatus.value = 'connected'
    }

    eventSource.value.onmessage = (event) => {
      // console.log('Received SSE message:', event.data)
      let data
      try {
        data = JSON.parse(event.data)
      } catch (e) {
        console.error('解析 SSE 数据失败:', e, '原始数据:', event.data)
        return
      }

      if (data.type && eventListeners[data.type]) {
        // console.log(`触发事件: ${data.type}， listeners: ${eventListeners[data.type].length}`)
        eventListeners[data.type].forEach(cb => {
          try {
            cb(data)
          } catch (e) {
            console.error(`执行事件 ${data.type} 回调失败:`, e)
          }
        })
      }
    }

    eventSource.value.onerror = (err) => {
      console.error('SSE 连接错误:', err)
      connectionStatus.value = 'disconnected'

      // 自动重连
      setTimeout(() => {
        console.log('尝试重新连接 SSE...')
        eventSource.value?.close()
        eventSource.value = null
        initEventBus()
      }, 3000)
    }
  } catch (e) {
    console.error('初始化 SSE 连接失败:', e)
    connectionStatus.value = 'disconnected'
    // 重试
    setTimeout(() => {
      initEventBus()
    }, 3000)
  }
}

// 订阅事件
export function onEvent(type, callback) {
  if (!eventListeners[type]) {
    eventListeners[type] = []
  }
  eventListeners[type].push(callback)
}

// 取消订阅
export function offEvent(type, callback) {
  if (eventListeners[type]) {
    eventListeners[type] = eventListeners[type].filter(cb => cb !== callback)
  }
}